package pers.hxy.lookweather.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 负责与assets文件夹内有关文件的操作
 */
public class AssetUtil {
    private static final String TAG = AssetUtil.class.getSimpleName();

    /**
     * 读取sql文件，合为一行，去除注释
     * 注释只能单独写在一行，由'--'开头
     * 只能有一条语句
     * @param context context
     * @param filename sql文件在assets文件夹下的路径
     * @return sql语句字符串，如果出错则返回空字符串
     */
    public static String readSqlFile(Context context, String filename) {
        AssetManager assetManager = context.getAssets();
        StringBuilder sql = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(assetManager.open(filename)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.isEmpty() && !line.startsWith("--")) {
                    sql.append(line);
                }
            }
        } catch (IOException e) {
            Log.i(TAG, e.toString());
        }
        return sql.toString();
    }

    /**
     * 读取CSV文件
     * @param context context
     * @param filename csv文件在assets下的路径
     * @return BufferedReader or null
     */
    public static BufferedReader readCSV(Context context, String filename) {
        AssetManager assetManager = context.getAssets();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(assetManager.open(filename)));
        } catch (IOException e) {
            Log.i(TAG, e.toString());
        }
        return reader;
    }
}
